﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using SuppKids.Core.Domain;
using SuppKids.Core.Services;
using SuppKids.Resources;

namespace SuppKids.Converters
{
	public class DishDisplayConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var dish = value as Dish;
			var dailyMenu = parameter as DailyMenu;
			if (dish != null && dailyMenu != null)
			{
				var app = (App)Application.Current;
				var groups = app.Container.Resolve<GroupService>().GetAll();
				var dishService = app.Container.Resolve<DishService>();

				foreach (var @group in groups)
				{
					var amount = dish.DishAmounts.FirstOrDefault(a => a.Group.Id == @group.Id && a.DailyMenu.Id == dailyMenu.Id) ?? new DishAmount(@group, dailyMenu);

					if (amount.IsTransient)
					{
						dish.DishAmounts.Add(amount);
						dishService.RegisterSave(dish, true);
					}
				}
				return string.Format(Labels.DishFormat, dish.Name, dish.DishAmounts.Where(a => a.DailyMenu.Id == dailyMenu.Id).Aggregate(string.Empty, (current, amount) => current + amount.Amount + "\\").TrimEnd('\\'));
			}

			return string.Empty;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}